import BASE_URL from '@/api/env.js' //引入接口共用地址
import Config from '@/utils/config.js'
import RequestManager from '@/utils/requestManager.js'
import {toast, clearStorageSync, getStorageSync, useRouter} from '@/utils/utils.js'

const manager = new RequestManager()

const baseRequest = async (url, method, data = {}, loading = true) =>{
	let requestId = manager.generateId(method, url, data)
	if(!requestId) {
		console.log('重复请求')
	}
	if(!requestId)return false;

	const header = {}
	const token  = getStorageSync('token') || ''
	header["token"]=token
	header["Content-type"]='application/json;charset=utf8'
	return new Promise((reslove, reject) => {
		loading && uni.showLoading({title: 'loading'})
		if (data) {
			data.appid=Config.appId
			data.appname=Config.appName
		}

		uni.request({
			url: BASE_URL + url,
			method: method || 'GET',
			header: header,
			timeout: 10000,
			data: data || {},
			complete: ()=>{
				uni.hideLoading()
				manager.deleteById(requestId)
			},
			success: (successData) => {

				console.log("url: %s \n请求参数：%o \n返回参数：%o",url,data,successData.data);
				const res = successData.data
				if(successData.statusCode == 200){
					let msg = res.msg
					if (res.code==1) { //成功
						reslove(res.data)
					} else if (
							res.code==101 // 广告次数已达上限
							|| res.code==102 // 金豆不足
							|| res.code==105 // 解锁卡不足
					) {
						reslove(res)
					}else { // 提示错误
						toast(msg)
						reslove(null)
					}
				}else{
					if (res.code==401) {
						toast(res.msg);
						reject(res)
						return;
					}
					console.log('网络连接失败，请稍后重试' ,url)
					toast('网络连接失败，请稍后重试')
					reject(res)
				}
			},
			fail: (msg) => {
				console.log("请求："+BASE_URL + url +'，发生错误：', err)
				toast('网络连接失败，请稍后重试')
				reject(msg)
			}
		})
	})
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})

export default request
